<script setup lang="ts">
import { uploadImageAPI } from '@/apis/consult';
import type { Image } from '@/types/consult';
import { showLoadingToast, showToast, type UploaderAfterRead } from 'vant';
import { ref } from 'vue';

//接收父组件提交过来的数据
defineProps<{
    disabled?: boolean
}>()

//定义响应式数据 
const message = ref('')

const emit = defineEmits<{
    'send-msg': [msg: string]
    'send-image': [img: Image]
}>()
//发送消息
const onSendmessage = () => {
    //判断用户是否输入了内容
    if (message.value.trim() === '') return showToast('请输入内容')
    //将搜集的数据发送给父组件
    emit('send-msg', message.value)
    //将输入框清空
    message.value = ''
}

const onAfterRead: UploaderAfterRead = async (item) => {
    // console.log(item)
    if (Array.isArray(item)) return
    if (!item.file) return
    const s = showLoadingToast({ message: '图片正在上传中', duration: 0 })
    // 调用文件上传的接口
    const res = await uploadImageAPI(item.file)
    s.close()
    // 将图片的数据提交给父组件
    emit('send-image', res.data)
}
</script>

<template>
    <div class="room-action">
        <van-field type="text" class="input" :border="false" placeholder="问医生" autocomplete="off" :disabled="disabled"
            v-model="message" @keydown.enter="onSendmessage"></van-field>
        <van-uploader :preview-image="false" :disabled="disabled" :after-read="onAfterRead">
            <cp-icon name="consult-img" />
        </van-uploader>
    </div>
</template>

<style lang="scss" scoped>
.room-action {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 60px;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding: 0 16px;
    z-index: 1;
    box-sizing: border-box;

    .input {
        background-color: var(--cp-bg);
        border: none;
        border-radius: 25px;
        margin-right: 10px;
        padding: 8px 15px;
    }

    .cp-icon {
        width: 24px;
        height: 24px;
    }
}
</style>